/**
 * 第四步：项目架构配置组件
 * 包含域名代理、状态管理、布局、路由、初始组件、API配置
 */
import React, { useEffect, useMemo } from 'react';
import { Form, Select, Input, Card, Row, Col, Typography, Radio, Tag } from 'antd';
import { FormInstance } from 'antd';
import styles from './ProjectArchitectureStep.module.css';
import { useSelector } from 'react-redux';
import { RootState } from '@/types';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;

interface ProjectArchitectureStepProps {
  form: FormInstance;
  onArchitectureChange?: (architecture: any) => void;
}



const ProjectArchitectureStep: React.FC<ProjectArchitectureStepProps> = ({ 
  form, 
  onArchitectureChange 
}) => {
  
  const uiFramework = Form.useWatch('uiFramework', form) || 'react';
  const watchedBaseComponents = Form.useWatch<string[]>('baseComponents', form);
  const watchedExtendedComponents = Form.useWatch<any[]>('extendedComponents', form);
  const selectedBaseComponents = useMemo(
    () => (watchedBaseComponents ?? form.getFieldValue('baseComponents') ?? []) as string[],
    [watchedBaseComponents, form]
  );
  const extendedComponentsForDisplay = useMemo(
    () => (watchedExtendedComponents ?? form.getFieldValue('extendedComponents') ?? []) as Array<string | Record<string, any>>,
    [watchedExtendedComponents, form]
  );
  const baseComponentDefinitions = useSelector((state: RootState) => state.project.baseComponents);

  const requiredBaseComponents = useMemo(() => {
    const explicit = baseComponentDefinitions
      .filter(component => component.required)
      .map(component => component.name);
    if (explicit.length > 0) {
      return explicit;
    }
    return baseComponentDefinitions.slice(0, 2).map(component => component.name);
  }, [baseComponentDefinitions]);

  const displayedBaseComponents = useMemo(
    () => Array.from(new Set([...requiredBaseComponents, ...selectedBaseComponents])),
    [requiredBaseComponents, selectedBaseComponents]
  );
  
  // 使用 useMemo 确保选项列表能正确响应框架变化
  const stateManagementOptions = useMemo(() => {
    if (uiFramework === 'react') {
      return [
        { label: 'Redux Toolkit', value: 'redux-toolkit' },
        { label: 'Zustand', value: 'zustand' },
        { label: 'Context API', value: 'context' },
        { label: '不使用状态管理', value: 'none' }
      ];
    } else if (uiFramework === 'vue') {
      return [
        { label: 'Pinia', value: 'pinia' },
        { label: 'Vuex', value: 'vuex' },
        { label: '不使用状态管理', value: 'none' }
      ];
    }
    return [];
  }, [uiFramework]);

  // 路由选项
  const routerOptions = useMemo(() => {
    if (uiFramework === 'react') {
      return [
        { label: 'React Router', value: 'react-router' },
        { label: 'Next.js Router (如果使用Next.js)', value: 'nextjs-router' },
        { label: '不使用路由', value: 'none' }
      ];
    } else if (uiFramework === 'vue') {
      return [
        { label: 'Vue Router', value: 'vue-router' },
        { label: 'Nuxt.js Router (如果使用Nuxt.js)', value: 'nuxtjs-router' },
        { label: '不使用路由', value: 'none' }
      ];
    }
    return [];
  }, [uiFramework]);
  
  // 当框架变化时，清空已选择的状态管理和路由选项
  useEffect(() => {
    // 清空可能不兼容的选项
    const currentStateManagement = form.getFieldValue('stateManagement');
    const currentRouter = form.getFieldValue('router');
    
    // 检查当前选择是否与新框架兼容
    const isStateManagementValid = stateManagementOptions.some(option => option.value === currentStateManagement);
    const isRouterValid = routerOptions.some(option => option.value === currentRouter);
    
    if (!isStateManagementValid) {
      form.setFieldValue('stateManagement', undefined);
    }
    if (!isRouterValid) {
      form.setFieldValue('router', undefined);
    }
  }, [uiFramework, form, stateManagementOptions, routerOptions]);
  
  // 布局选项 - 图形化展示
  const layoutOptions = [
    {
      label: 'Header + Sidebar + Content',
      value: 'sidebar-layout',
      icon: (
        <div className={`${styles.layoutIcon} ${styles.sidebarLayout}`}>
          <div className={styles.sidebarLayoutHeader}></div>
          <div className={styles.sidebarLayoutBody}>
            <div className={styles.sidebarLayoutSidebar}></div>
            <div className={styles.sidebarLayoutContent}></div>
          </div>
        </div>
      )
    },
    {
      label: 'Header + Content + Footer',
      value: 'header-footer-layout',
      icon: (
        <div className={`${styles.layoutIcon} ${styles.headerFooterLayout}`}>
          <div className={styles.headerFooterHeader}></div>
          <div className={styles.headerFooterContent}></div>
          <div className={styles.headerFooterFooter}></div>
        </div>
      )
    },
    {
      label: 'Tab式布局',
      value: 'tab-layout',
      icon: (
        <div className={`${styles.layoutIcon} ${styles.tabLayout}`}>
          <div className={styles.tabLayoutHeader}>
            <div className={styles.tabLayoutTab1}></div>
            <div className={styles.tabLayoutTab2}></div>
          </div>
          <div className={styles.tabLayoutContent}></div>
        </div>
      )
    },
    {
      label: '单页面布局',
      value: 'single-page',
      icon: (
        <div className={`${styles.layoutIcon} ${styles.singlePageLayout}`}>
        </div>
      )
    },
    {
      label: '自定义布局',
      value: 'custom',
      icon: (
        <div className={`${styles.layoutIcon} ${styles.customLayout}`}>
          <div className={styles.customLayoutBlock1}></div>
          <div className={styles.customLayoutBlock2}></div>
          <div className={styles.customLayoutBlock3}></div>
          <div className={styles.customLayoutBlock4}></div>
        </div>
      )
    }
  ];
  
  // 监听架构配置变化
  const handleValueChange = (changedValues: any, allValues: any) => {
    if (onArchitectureChange) {
      onArchitectureChange(allValues);
    }
  };

  return (
    <div>
      <Title level={4}>项目架构配置</Title>
      <Text type="secondary">
        配置项目的核心架构，包括域名代理、状态管理、路由等关键模块
      </Text>

      <Form.Provider onFormChange={handleValueChange}>
        <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
          {/* 域名代理配置 */}
          <Col span={24}>
            <Card title="域名代理配置" size="small">
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Form.Item
                    name="devProxy"
                    label="开发环境API"
                    tooltip="开发环境的后端API地址"
                  >
                    <Input placeholder="http://localhost:3001" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    name="testProxy"
                    label="测试环境API"
                    tooltip="测试环境的后端API地址"
                  >
                    <Input placeholder="https://test-api.example.com" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    name="prodProxy"
                    label="生产环境API"
                    tooltip="生产环境的后端API地址"
                  >
                    <Input placeholder="https://api.example.com" />
                  </Form.Item>
                </Col>
              </Row>
            </Card>
          </Col>

          {/* 状态管理 */}
          <Col span={12}>
            <Card title="状态管理" size="small">
              <Select 
                placeholder="选择状态管理方案"
                className={styles.selectFullWidth}
                onChange={(value) => form.setFieldValue('stateManagement', value)}
              >
                  {stateManagementOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
                {/* 添加调试信息 */}
                <div className={styles.debugInfo}>
                  当前框架: {uiFramework}, 选项数: {stateManagementOptions.length}
                </div>
            </Card>
          </Col>

          {/* 路由配置 */}
          <Col span={12}>
            <Card title="路由配置" size="small">
              <Select 
                placeholder="选择路由方案"
                className={styles.selectFullWidth}
                onChange={(value) => form.setFieldValue('router', value)}
              >
                  {routerOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
                {/* 添加调试信息 */}
                <div className={styles.debugInfo}>
                  路由选项数: {routerOptions.length}
                </div>
            </Card>
          </Col>
        {/* 扩展组件 */}
          <Col span={12}>
            <Card title="组件" size="small" className={styles.equalHeightCard}>
              <div className={styles.componentGroup}>
                <div className={styles.componentGroupTitle}>基础组件</div>
                {displayedBaseComponents.length === 0 ? (
                  <Text type="secondary">上一环节未选择基础组件</Text>
                ) : (
                  <div className={styles.tagContainer}>
                    {displayedBaseComponents.map((componentName: string) => {
                      const definition = baseComponentDefinitions.find(item => item.name === componentName);
                      const isRequired = definition?.required || requiredBaseComponents.includes(componentName);
                      return (
                        <Tag key={`base-${componentName}`} color={isRequired ? 'red' : 'blue'}>
                          {componentName}
                          {isRequired ? '（必需）' : ''}
                        </Tag>
                      );
                    })}
                  </div>
                )}
              </div>
              <div className={styles.componentGroup}>
                <div className={styles.componentGroupTitle}>扩展组件</div>
                {extendedComponentsForDisplay.length === 0 ? (
                  <Text type="secondary">上一环节未选择扩展组件</Text>
                ) : (
                  <div className={styles.tagContainer}>
                    {extendedComponentsForDisplay.map((component) => {
                      const componentLabel = (() => {
                        if (typeof component === 'string') {
                          return component;
                        }
                        const recordComponent = component as Record<string, any>;
                        return (
                          recordComponent.name ||
                          recordComponent.label ||
                          JSON.stringify(recordComponent)
                        );
                      })();
                      return (
                        <Tag key={`extended-${componentLabel}`} color="purple">
                          {componentLabel}
                        </Tag>
                      );
                    })}
                  </div>
                )}
              </div>
            </Card>
          </Col>
        {/* 额外配置 */}
          <Col span={12}>
            <Card title="补充配置" size="small" className={styles.equalHeightCard}>
              <Form.Item
                name="additionalConfig"
                label="其他需求"
                tooltip="描述其他特殊的架构需求"
              >
                <TextArea 
                  placeholder="例如：需要PWA支持、国际化、主题切换等..." 
                  rows={6} 
                  maxLength={500}
                />
              </Form.Item>
            </Card>
          </Col>
          {/* 布局配置 */}
          <Col span={24}>
            <Card title="布局配置" size="small">
              <Form.Item
                name="layout"
                label="页面布局"
                tooltip="选择项目的主要布局结构"
              >
                <Radio.Group>
                  <Row gutter={[16, 16]}>
                    {layoutOptions.map(option => (
                      <Col key={option.value} span={8}>
                        <Radio.Button 
                          value={option.value}
                          className={`${styles.layoutOption} ${form.getFieldValue('layout') === option.value ? styles.layoutOptionSelected : ''}`}
                        >
                          <div className={styles.layoutOptionContent}>
                            {option.icon}
                            <div className={styles.layoutOptionLabel}>
                              {option.label}
                            </div>
                          </div>
                        </Radio.Button>
                      </Col>
                    ))}
                  </Row>
                </Radio.Group>
              </Form.Item>
            </Card>
          </Col>
          

        </Row>
      </Form.Provider>
    </div>
  );
};

export default ProjectArchitectureStep;
